package com.yc.starter.vcode.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.starter.vcode.dto.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author navy
 * @company 源辰信息
 * @date 2024/9/10
 * @email haijunzhou@hnit.edu.cn
 */
public class VcodeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object vcode = request.getSession().getAttribute("vcode");
        String vcode1 = request.getParameter("vcode");
        Result result = null;
        if(vcode == null){
            result = new Result(-1,"未生成验证码",null);
        } else if(vcode1 == null){
            result = new Result(-2,"未输入验证码",null);
        } else if(vcode.toString().equalsIgnoreCase(vcode1) == false){
            result = new Result(-3,"验证码输入错误",null);
        } else {
            request.getSession().removeAttribute("vcode");
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().append(json);
        return false;
    }
}
